import { execSync } from 'child_process';
import fs from 'fs';
import jszip from 'jszip'

/**
 * @type {ssh2.ConnectConfig}
 */
const LOCAL_PATH = "./build";
const LOCAL_PATH_TAR = "./build/bundles";

const PackRec = async (zf, path) => {
    const fsDir = fs.opendirSync(path);
    let childDirent = fsDir.readSync();
    while (childDirent) {
        if (childDirent.isDirectory()) {
            let czf = zf.folder(childDirent.name);
            await PackRec(czf, path + childDirent.name + "/");
        }
        else {
            zf.file(childDirent.name, fs.readFileSync(path + childDirent.name));
        }
        childDirent = fsDir.readSync();
    }
    fsDir.closeSync();
};

const CompressRec = async (path) => {
    const fsDir = fs.opendirSync(path);
    let childDirent = fsDir.readSync();
    while (childDirent) {
        if (childDirent.isDirectory()) {
            await CompressRec(path + childDirent.name + "/");
        }
        else {
            if (childDirent.name.split(".")[1] == "png") {
                await execSync(`pngquant -f --ext .png --quality 10-90 --speed 1 "${path + childDirent.name}"`);
                console.log(`pngquant: 压缩图片"${path + childDirent.name}"`);
            }
        }
        childDirent = fsDir.readSync();
    }
};

//=======================================================================
let argvs = process.argv;
let build_target = argvs[2];
let bundleList = argvs.slice(3);
if (!(build_target == "test" || build_target == "res") || !bundleList || bundleList.length === 0) {
    console.log("build_target [ bundle_name_list...]");
    process.exit(0);
}
console.table(bundleList);

if( !fs.existsSync( LOCAL_PATH_TAR)){
    fs.mkdirSync(LOCAL_PATH_TAR);
}

for (let i = 0; i < bundleList.length; i++) {
    let bundleName = bundleList[i];
    let bundlePath = `${LOCAL_PATH_TAR}/${bundleName}`;
    fs.mkdirSync(bundlePath);
    //复制文件。
    let copyStatment = `xcopy /y /c /s /h /r ` + `"${LOCAL_PATH}\\web-mobile\\assets\\${bundleName}\\*.*" "${LOCAL_PATH_TAR}\\${bundleName}\\" `.replaceAll("./", "").replaceAll("/", "\\");
    execSync(copyStatment);

    //修改文件
    let fileStr = fs.readFileSync(`${LOCAL_PATH_TAR}/${bundleName}/index.js`).toString();

    fileStr =
        fileStr.replace(new RegExp(`BUNDLE_${bundleName.toUpperCase()}_BUILD_TARGET="(.+?)"`, "g"), `BUNDLE_${bundleName.toUpperCase()}_BUILD_TARGET="${build_target}"`)
        ;
    fs.writeFileSync(`${LOCAL_PATH_TAR}/${bundleName}/index.js`, fileStr);

    //压缩
    await CompressRec(`${bundlePath}/`);

    //打包
    let zipPath = `${LOCAL_PATH_TAR}/${bundleName}.zip`;
    {
        const zip = new jszip();
        let zf = zip.folder(bundleName);
        await PackRec(zf, `${bundlePath}/`);
        let content = await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" });
        fs.writeFileSync(zipPath, content);
    }
    console.log("完成：", zipPath);
}

process.exit(0);